package com.sh.滑动时间窗口算法;


import com.sh.RateLimiter;

import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SlidingWindowRateLimiter implements RateLimiter {
    private int reqCount; // 请求计数器
    private LinkedList<Integer>  slots = new LinkedList<>(); // 滑动窗口
    private int limitNum = 100;   // 每秒限流的最大请求数
    private long windowLength = 100L; // 每个窗口长度 100ms
    private int windowNum = 10;  // 窗口数量
    private final Lock lock = new ReentrantLock();


    // true 通过 false 不通过
    public synchronized boolean limit() {
//        lock.lock();
        try {
            if ((reqCount + 1) > limitNum) {
                return false;
            }
            slots.set(slots.size() - 1, slots.peekLast() + 1);
            reqCount++;
            return true;
        } finally {
//            lock.unlock();
        }

    }

    public SlidingWindowRateLimiter(){
        slots.addLast(0);
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(windowLength);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                lock.lock();
                try {
                    slots.addLast(0);
                    if (slots.size() > windowNum) {
                        reqCount = reqCount - slots.peekFirst();
                        slots.removeFirst();
                        System.out.println("滑动格子：" + reqCount);
                    }
                } finally {
//                    lock.unlock();
                }
            }
        }).start();
    }

}